using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace LetLord.Models
{ 
    public class TenantGroupMemberRepository : ITenantGroupMemberRepository
    {
        LetLordContext context = new LetLordContext();

        public IQueryable<TenantGroupMember> All
        {
            get { return context.TenantGroupMember; }
        }

        public IQueryable<TenantGroupMember> AllIncluding(params Expression<Func<TenantGroupMember, object>>[] includeProperties)
        {
            IQueryable<TenantGroupMember> query = context.TenantGroupMember;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public TenantGroupMember Find(int id)
        {
            return context.TenantGroupMember.Find(id);
        }

        public void InsertOrUpdate(TenantGroupMember tenantgroupmember)
        {
            if (tenantgroupmember.TenantGroupMemberId == default(int)) {
                // New entity
                var tgm = context.TenantGroupMember.Create();
                tgm.TenantGroupMemberName = tenantgroupmember.TenantGroupMemberName;
                tgm.TenantGroupMemberAge = tenantgroupmember.TenantGroupMemberAge;
                var loggedIn = context.UserProfile.OfType<Tenant>().First(t => t.UserName == System.Web.HttpContext.Current.User.Identity.Name);
                tgm.UserId = loggedIn.UserId;
                context.TenantGroupMember.Add(tgm);
                context.SaveChanges();
            } else {
                // Existing entity
                context.Entry(tenantgroupmember).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var tenantgroupmember = context.TenantGroupMember.Find(id);
            context.TenantGroupMember.Remove(tenantgroupmember);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose() 
        {
            context.Dispose();
        }
    }

    public interface ITenantGroupMemberRepository : IDisposable
    {
        IQueryable<TenantGroupMember> All { get; }
        IQueryable<TenantGroupMember> AllIncluding(params Expression<Func<TenantGroupMember, object>>[] includeProperties);
        TenantGroupMember Find(int id);
        void InsertOrUpdate(TenantGroupMember tenantgroupmember);
        void Delete(int id);
        void Save();
    }
}